﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using Fasterflect;
using System.ComponentModel.Design;

namespace NanoERP.Infrastructure
{
    public partial class FormBase : DockContent
    {

        private IList<string> _moduleNames;

        protected IList<string> ModuleNames
        {
            get
            {
                if (_moduleNames == null)
                {
                    var names = ModuleAttribute.GetModuleNames(this.GetType());
                    if (names == null)
                        return new List<string>();
                    _moduleNames = names.ToList();
                }
                return _moduleNames;
            }
        }

        private IList<string> Rights { get; set; }

        public FormBase()
        {
            InitializeComponent();
            if (IsDesignMode)
                return;
            InitRightsInfo();
        }

        /// <summary>
        /// 初始化权限信息
        /// </summary>
        private void InitRightsInfo()
        {
            if (ModuleNames.Count < 1)
                return;
            Rights = AuthHelper.GetRights(LogonSession.LogonUser, ModuleNames);
        }

        protected override void OnLoad(EventArgs e)
        {
            if (IsDesignMode)
                return;

            if (!HasViewRight())
            {
                MessageBox.Show(this, "无权限访问", "警告", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                this.Enabled = false;
                return;
            }
            base.OnLoad(e);
        }

        private bool HasViewRight()
        {
            return this.HasRight("View");
        }

        protected virtual bool HasRight(string rightCode)
        {
            if (Rights == null)
                return true;
            //在这里添加权限验证方法
            return Rights.Contains(rightCode);

            //return ModuleNames == null
            //    || ModuleNames.Count < 1
            //    || this.ModuleNames.Select(module => this.HasRight(rightCode)).FirstOrDefault();

            //return MessageBox.Show(this,
            //    string.Format("模块{0}正在请求验证{1}功能,允许？", moduleName, rightName),
            //    "调试模式", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes;
            //return true;
        }

        protected virtual bool IsDesignMode
        {
            get
            {
                return this.GetService(typeof(IDesignerHost)) != null
                    || LicenseManager.UsageMode == LicenseUsageMode.Designtime;
            }
        }
    }
}
